package cn.datawin.co.corule.service;

import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import cn.datawin.co.corule.service.client.CoClient;
import cn.datawin.co.corule.service.client.CoService;
import cn.datawin.service.BaseService;

import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

/**
 * 
 *@author zhangke
 *获取result
 *
 */
@Service
public class CoTaskResultPoll extends BaseService{
	

	/* 保存client */
	private Hashtable<String,CoClient> clients = new Hashtable<String, CoClient>();
	
	public void setClient(CoClient client){
		clients.put(client.getClientid(),client);
	}
	
	public CoClient getClient(String clientid){
		return clients.get(clientid);
	}
	
	
//	@PostConstruct
	void r(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					try{
						runresult();
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
	
	List<DBObject> findCoTaskResult(int times){
		List<DBObject> list = this.findList("cotaskResult",new BasicDBObject("state","0"));
		if(list.size()==0){
			while(times<10){
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {}
				times++;
				return findCoTaskResult(times);
			}
		}
		return list;
	}
	
	public void runresult(){
		List<DBObject>  list = findCoTaskResult(1);
		if(null!=list&&list.size()>0){
			for(DBObject r:list){
				CoClient client = clients.get(r.get("clientid").toString());
				if(null!=client){
					CoService service = (CoService) client.getService(r.get("taskid").toString());
					if(null!=service){
						service.dooResult(r);
					}
				}
				r.put("state","1");
				this.updateByid("cotaskResult",r.get("_id").toString(),r);
			}
		}
	}
	

}
